<?php
//http://stackoverflow.com/questions/8840319/build-a-tree-from-a-flat-array-in-php
function buildTree(array &$elements, $parentId = 0) {
   $branch = array();
   foreach ($elements as $element) {
	   if ($element['parent_id'] == $parentId) {
		   $children = buildTree($elements, $element['id']);
		   if ($children) {
			   $element['children'] = $children;
		   }
		   $branch[$element['id']] = $element;
		   unset($elements[$element['id']]);
	   }
   }
   return $branch;
}

